package com.cxh.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.cxh.entity.Item;
import com.cxh.enums.ExceptionInfoEnum;
import com.cxh.exception.SsmException;
import com.cxh.mapper.ItemMapper;
import com.cxh.service.ItemService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Slf4j
@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    public ItemMapper itemMapper;

    @Override
    public PageInfo<Item> findProductByNameLimit(String name, Integer page, Integer size) {
        PageHelper.startPage(page,size);
        Example example = new Example(Item.class);
        Example.Criteria c = example.createCriteria();
        if (!StringUtils.isEmpty(name)) {
            c.andLike("name", "%" + name + "%");
        }
        List<Item> list = itemMapper.selectByExample(example);
        PageInfo<Item> pageInfo = new PageInfo<>(list);

        return pageInfo;
    }

    @Override
    public Integer add(Item item) {
        int result = itemMapper.insertSelective(item);
        if (result != 1){
            log.error("【添加商品】 添加商品失败!  item = {}",item);
            throw new SsmException(ExceptionInfoEnum.ITEM_ADD_ERROR);
        }
       return result;
    }

    @Override
    public Integer delete(Integer id) {
        int result = itemMapper.deleteByPrimaryKey(id);
        if (result !=1){
            log.error("【删除商品】 删除商品失败!  id = {}",id);
            throw new SsmException(ExceptionInfoEnum.ITEM_DELETE_ERROR);
        }
        return result;
    }

    @Override
    public Item findEntityById(Integer id) {
        Item item = itemMapper.selectByPrimaryKey(id);
        if (item==null){
            log.error("【修改商品】 查询单个商品失败!  id = {}",id);
            throw new SsmException(ExceptionInfoEnum.ITEM_SELECTONE_ERROR);
        }
        return item;
    }

    @Override
    public Integer updateEntityById(Item item) {
        int result = itemMapper.updateByPrimaryKeySelective(item);
        if (result !=1){
            log.error("【修改商品】 查询单个商品失败!  item = {}",item);
            throw new SsmException(ExceptionInfoEnum.ITEM_UPDATEONE_ERROR);
        }
        return result;
    }
}
